const fs = require('fs')
const path = require('path')
const cloudset = require('configs/cloudset')
const {envid, appid, scope, appsecret} = cloudset

const cloudApis = {
  token: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET',
  databaseCollectionDelete: 'https://api.weixin.qq.com/tcb/databasecollectiondelete',
  
  // 批量删除存储文件，比如图片
  diskDeleteFile: 'https://api.weixin.qq.com/tcb/batchdeletefile?access_token=ACCESS_TOKEN'
}

const cloudApisFunction = {
  async token(ctx){
    let url = cloudApis['token']
    url = url.replace('APPID', appid).replace('APPSECRET', appsecret)
    const token = await Fetcher.get(url)
    return token
  },

  /**
   * param: {
   *   access_token,
   *   env,
   *   collection_name
   * }
   */
  async databaseCollectionDelete(ctx, param={}, token){
    let url = cloudApis['databaseCollectionDelete']
    url = url.replace('ACCESS_TOKEN', token)
    param.access_token = token
    param.env = envid
    return await Fetcher.post(url, param)
  },

  /**
   * param: {
   *   access_token,
   *   env,
   *   collection_name
   * }
   */
  async diskDeleteFile(ctx, param={}, token){
    let url = cloudApis['diskDeleteFile']
    url = url.replace('ACCESS_TOKEN', token)
    param.env = envid
    // param.fileid_list = []
    return await Fetcher.post(url, param)
  }
}

async function apiControl(ctx, next){
  const aks = ctx.aks
  const isAjax = aks.isAjax()
  let   route = aks.routePath
  route = route.replace('/api/', '').replace('api/', '')
  const token = await Cache.ifid('token-for-cloud', async function(){
    let res = await cloudApisFunction['token'](ctx)
    Cache.set('token-for-cloud', res.access_token, (res.expires_in*1000)) // access_token, expires_in
    return res.access_token
  })

  let body = null
  let param = null
  if (cloudApis[route] && token) {
    body = ctx.request.body
    param = body.body
    ctx.body = await cloudApisFunction[route](ctx, param, token)
    return 
  }

  ctx.body = {success: true}
}

// 自定义路由  
export default function(aks, app){

  // 前端通过 Fetcher.get 或者 Fetcher.post 向node端发起资源请求
  // await Fetcher.get('/api/test')  查看configs/default中的apis字段
  aks.routepreset('/api', {
    customControl: apiControl
  })
}
